import  requests
from bs4 import BeautifulSoup
import datetime
url="https://sh.esf.fang.com/"
i=31
yeshu=input("输入爬取页数")
fp=open(f"csv/{datetime.datetime.now()}.csv",mode='w')
while (i<=(30+int(yeshu))):
    url_next=url+f"house/i{i}"
    print("等待服务器",end='\r')
    res=requests.get(url_next)
    page=BeautifulSoup(res.text,"html.parser")
    print("已获得页面"+url_next)
    total=page.find("div",class_="shop_list shop_list_4")
    houses=total.find_all("dl",class_="clearfix")
    for house in houses:
        name=house.find("h4",class_="clearfix").find("span").text
        text1=house.find("p",class_="tel_shop").text
        text1=text1.split("|")
        room=text1[0]
        mianji=text1[1]
        louceng=text1[2]
        chaoxiang=text1[3]
        year=text1[4]
        master=house.find("p",class_="tel_shop").find("a").text
        address = house.find("p", class_="add_shop").find("a").text
        price=house.find("dd",class_="price_right").find("b").text
        average_price=(house.find("dd",class_="price_right").find_all("span"))[1].text
        print(f"{name},{room},{mianji},{louceng},{chaoxiang},{year},{master},{address},{price}万,{average_price}",file=fp)
    i+=1

